package cn.net.Serializable;
/**本类测试序列化和反序列化；序列化和反序列化成对出现，成对执行*/
/*
    序列化输出:ObjectOutputStream
    反序列化读取:ObjectInputStream
 */
import java.io.*;

public class TestStudent {
    public static void main(String[] args) {
        method();//序列化:ObjectOutputStream----out.writeObject()
        method2();//反序列化:ObjectInputStream---in.readObject()

    }

    private static void method2() {//读入;反序列化方法
        ObjectInputStream in = null;//导包
        try {
            in = new ObjectInputStream(new FileInputStream("D:\\File\\1.txt"));
            ////2.通过流对象反序列化生成指定对象
            System.out.println(in.readObject());//读取对象打印出来

            System.out.println("恭喜你!反序列化成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("很抱歉!反序列化失败!");
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void method() {//写出;序列化方法
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream("D:\\File\\1.txt"));
            //2.指定要序列化(输出)的对象
            Student s = new Student("小王",18,'男',20210620);
            //out.write(s);报错！！
            out.writeObject(s);//调用writeObject()方法即可，无需打印

            System.out.println("恭喜你!序列化成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("很抱歉!序列化失败!");
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
